package com.weisy.signin.network.resource;

import android.text.TextUtils;
import android.util.Log;

import com.weisy.signin.bean.MsgEvent;
import com.weisy.signin.bean.Student;
import com.weisy.signin.comm.Comm;
import com.weisy.signin.network.utils.HttpContext;
import com.weisy.signin.network.utils.StreamToolkit;
import com.weisy.signin.utils.GsonUtils;
import com.weisy.signin.utils.Logs;

import org.litepal.LitePal;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.List;

import kotlin.text.Charsets;

/**
 * @author weisy
 * @function 成绩接口
 * @date 2019/3/22 21:54
 */
public class ScoreResourceUriHandler implements IResourceUriHandler {
    private String TAG = "ScoreResourceUriHandler";
    private String suffix = "/score";

    public ScoreResourceUriHandler() {
    }

    @Override
    public boolean accept(String uri) {
        return uri.equals(suffix);
    }

    @Override
    public void handle(String uri, HttpContext httpContext) {
        Log.d(TAG, "uri=" + uri);
        String assetsPath = uri.substring(suffix.length());
        try {
            InputStream ins = httpContext.underlySocket.getInputStream();
            String readLine;
            while ((readLine = StreamToolkit.readContent(ins)) != null) {
                if (TextUtils.isEmpty(readLine)) {
                    break;
                }
                Logs.d(TAG, "data=" + readLine);
                Student student = GsonUtils.str2Bean(readLine, Student.class);
                List<Student> tmp = LitePal.where("studentId=?", student.getStudentId()).find(Student.class);
                String msg = "";
                if (null == tmp || tmp.isEmpty()) {
                    msg = "您还未签到，签到之后才能产生成绩表";
                }else {
                    student.setScore(tmp.get(0).getScore());
                    student.setMidScore(tmp.get(0).getMidScore());
                    student.setEndScore(tmp.get(0).getEndScore());
                }
                String response = GsonUtils.bean2Str(new MsgEvent(Comm.SIGN_SCORE, msg, GsonUtils.bean2Str(student)));
                Log.i(TAG, "响应消息："+response);
                OutputStreamWriter osw = new OutputStreamWriter(httpContext.underlySocket.getOutputStream(), Charsets.UTF_8);
                StringBuilder sb = new StringBuilder();
                sb.append("HTTP/1.1 200 OK\r\n");
                sb.append("Connection: keep-alive\r\n");
                sb.append("Content-length: ").append(response.length()).append("\r\n");
                sb.append(StreamToolkit.addContentType(assetsPath)).append("\r\n");
                sb.append("\r\n");
                sb.append(response).append("\r\n");
                osw.write(sb.toString());
                osw.flush();
                Log.d(TAG, "服务器响应了消息");
            }
        } catch (IOException e) {
            Logs.e(TAG, "ex:" + e.toString());
            e.printStackTrace();
        }
    }
}
